package cc.mrbird.febs.system.controller;


import cc.mrbird.febs.common.annotation.Log;
import cc.mrbird.febs.common.controller.BaseController;
import cc.mrbird.febs.common.domain.QueryRequest;
import cc.mrbird.febs.common.exception.FebsException;
import cc.mrbird.febs.system.domain.GroupUser;
import cc.mrbird.febs.system.domain.Role;
import cc.mrbird.febs.system.domain.User;
import cc.mrbird.febs.system.service.GroupService;
import cc.mrbird.febs.system.service.GroupUserService;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import cc.mrbird.febs.system.domain.Group;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 福小林
 */
@Slf4j
@Validated
@RestController
@RequestMapping("group")
public class GroupController extends BaseController {


    private String message;

    @Autowired
    private GroupService groupService;

    @Autowired
    GroupUserService groupUserService;

    /**
     * 小组管理列表数据查询
     *
     * @param queryRequest 查询请求
     * @param group        小组信息
     */
    @GetMapping
    @RequiresPermissions("group:view")
    public Map<String, Object> groupList(QueryRequest queryRequest, Group group) {
        return getDataTable(groupService.findGroupDetail(group, queryRequest));
    }


    @Log("新增小组")
    @PostMapping
    @RequiresPermissions("group:add")
    public void addUser(@Valid Group group) throws FebsException {
        try {
            String groupMemberIds = group.getGroupMemberIds();

            group.setCreateTime(LocalDate.now());
            group.setGroupMemberIds(null);
            this.groupService.save(group);
            Long groupId = group.getId();
            setGroupUserData(groupId, groupMemberIds);


        } catch (Exception e) {
            message = "新增小组失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @Log("根据科室id查询可用小组成员")
    @RequestMapping("/availableMember")
    public List<Map<String, Object>> availableMember(@Valid String deptId) {
        List<Map<String, Object>> availableMemberList = groupService.getAvailableMemberList(deptId);

        if (availableMemberList != null && !availableMemberList.isEmpty()) {
            Map<String, Object> stringObjectMap = availableMemberList.get(0);
            if (stringObjectMap != null && !stringObjectMap.isEmpty()) {
                return availableMemberList;
            }
        }
        return null;

    }


    @Log("修改小组")
    @PutMapping
    @RequiresPermissions("group:update")
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(@Valid Group group) throws FebsException {
        try {
            Long groupId = group.getId();
            String groupMemberIds = group.getGroupMemberIds();
            groupService.removeById(groupId);
            List<String> groupUserIds = groupService.getGroupUserIds(String.valueOf(groupId));
            groupUserService.removeByIds(groupUserIds);
            group.setGroupMemberIds(null);
            this.groupService.save(group);
            setGroupUserData(group.getId(), groupMemberIds);

        } catch (Exception e) {
            message = "修改小组失败";
            log.error(message, e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new FebsException(message);
        }
    }

    private void setGroupUserData(Long groupId, String groupMemberIds) {
        String[] split = groupMemberIds.split(StringPool.COMMA);
        for (String userId : split) {
            GroupUser groupUser = new GroupUser();
            groupUser.setUserId(userId);
            groupUser.setGroupId(String.valueOf(groupId));
            groupUserService.save(groupUser);
        }
    }

    @Log("删除小组")
    @DeleteMapping("/{groupIds}")
    @RequiresPermissions("group:delete")
    public void deleteUsers(@NotBlank(message = "{required}") @PathVariable String groupIds) throws FebsException {
        try {
            String[] ids = groupIds.split(StringPool.COMMA);
            for (String id : ids) {
                List<String> groupUserIds = groupService.getGroupUserIds(id);
                groupService.removeById(id);
                groupUserService.removeByIds(groupUserIds);
            }

        } catch (Exception e) {
            message = "删除小组失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }


    @PostMapping("excel")
    @RequiresPermissions("group:export")
    public void export(QueryRequest queryRequest, Group group, HttpServletResponse response) throws FebsException {
        try {
            List<Group> groupList = this.groupService.findGroupDetail(group, queryRequest).getRecords();
            ExcelKit.$Export(Group.class, response).downXlsx(groupList, false);
        } catch (Exception e) {
            message = "导出Excel失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }


}
